/*
 * Copyright [2011] [Ambud Sharma/ODep Monitor]

   Licensed under the Apache License, Version 2.0 (the "License");

   you may not use this file except in compliance with the License.

   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software

   distributed under the License is distributed on an "AS IS" BASIS,

   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

   See the License for the specific language governing permissions and

   limitations under the License.
 */
package edu.uwsp.orion.odepm.main.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import edu.uwsp.orion.odepm.main.client.JobLauncher;
import edu.uwsp.orion.odepm.main.shared.JobInfo;

public class JobLauncherImpl extends RemoteServiceServlet implements JobLauncher {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5300824402523680115L;

	@Override
	public boolean launch(JobInfo info) {
		boolean launchStatus = false;
		HadoopUtils utils=new HadoopUtils();
		String jarLocation=(String) this.getThreadLocalRequest().getSession().getAttribute("jarLocation");
		System.out.print(jarLocation);
		try {
			final Process p=Runtime.getRuntime().exec("/home/orion/Hadoop/bin/hadoop jar "+jarLocation+" "+info.inputDir+" "+info.outputDir);
			System.out.print(jarLocation);
			Thread th=new Thread(){
				@Override
				public void run() {
					BufferedReader reader=new BufferedReader(new InputStreamReader(p.getErrorStream()));
					String lin;
					try {
						while((lin=reader.readLine())!=null){
							System.err.println(lin);
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
			BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
			String lin;
			while((lin=reader.readLine())!=null){
				System.out.println(lin);
			}
			launchStatus=true;
		} catch (IOException e) {
			
			e.printStackTrace();
			launchStatus=false;
		}
		return launchStatus;
	}
}
